<?php

class Admin_Model_Users{

	private $userTbl;
	
	public function __construct(){
		$this->userTbl	= new Admin_Model_DbTable_Users();
	}

	public function selectUsers($where =NULL, $order = "tenDangNhap"){
		$dbAdapter	= Zend_Db_Table::getDefaultAdapter();
		$dbSelect = new Zend_Db_Select($dbAdapter);
		$dbSelect->from(array('u'=>'nguoidung'),"*");
//				->joinLeft(array('bv'=>'baiviet'), 'bv.tenDangNhap = u.tenDangNhap',
//							array('baiVietId','tieuDe','noiDung','ngayViet','menu2Id','trangThai','thungRac')
//				)

		if ($where!=null){
			$dbSelect->where($where);
		}
		
		$dbSelect->order($order);
		
		return $dbSelect;
	}
	
	public function addUser($tenDangNhap, $matKhau, $quyen, $hoTen, $ngaySinh, $ngayTao, $email ){
		$matKhau = md5($matKhau);
		$data = array(
			'tenDangNhap'	=> $tenDangNhap,
			'matKhau'		=> $matKhau,
			'quyen'			=> $quyen,
			'hoTen'			=> $hoTen,
			'ngaySinh'		=> $ngaySinh,
			'ngayTao'		=> $ngayTao,
			'email'			=> $email
		);		
		$this->userTbl->insert($data);
	}
	
	public function addCustomUser($data){
		$this->userTbl->insert($data);
	}
	
	public function updateUser($matKhau, $quyen, $hoTen, $ngaySinh, $ngayTao, $email,$tenDangNhap ){
		$matKhau = md5($matKhau);
		$data = array(			
			'matKhau'		=> $matKhau,
			'quyen'			=> $quyen,
			'hoTen'			=> $hoTen,
			'ngaySinh'		=> $ngaySinh,
			'ngayTao'		=> $ngayTao,
			'email'			=> $email
		);		
		$this->userTbl->update($data, "tenDangNhap ='".$tenDangNhap."'");
	}
	
	public function updateCustomUser($data,$where){
		$this->userTbl->update($data, $where);
	}
	
	public function deleteUser($tenDangNhap){
		$this->userTbl->delete("tenDangNhap ='".$tenDangNhap."'");
	}
	
	public function fetchAllUser($where=NULL){
		if ($where!=null) {
			return $this->userTbl->fetchAll($where);
		}else
			return $this->userTbl->fetchAll();
	}
	
	public function fetchRowUser($tenDangNhap){
		$data = array();
		foreach ($this->userTbl->fetchRow("tenDangNhap = '".$tenDangNhap."'") as $key=>$value) {
			$data[$key] = $value;
		}
		return $data;
	}
	
	/**
	 * 
	 * Lay du lieu cua tat ca cac cot trong array column
	 * @param unknown_type $colArr: danh sach cac cot
	 */
	public function fetchCol($colArr,$where=NULL){
		$sql = "SELECT ";
		for($i =0; $i<count($colArr); $i++){
			if($i != count($colArr)-1)
				$sql .= " ".$colArr[$i]."," ;
			else 
				$sql .= " ".$colArr[$i];
		}
		$sql .=" FROM baiViet ";
		
		if ($where!=NULL){
			$sql .= " WHERE ".$where;	
		}
		return $this->postTbl
					->getAdapter()
					->fetchAll($sql);
	}
	
}

